package com.dbpms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dbpms.mapper.ChamberMapper;
import com.dbpms.mapper.StudentManageMapper;
import com.dbpms.pojo.*;
import com.dbpms.service.IStudentManageService;
import com.dbpms.service.ITransferService;
import com.dbpms.until.Constants;
import com.dbpms.until.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.List;

@Controller
@RequestMapping("/studentManage")
public class StudentManageController {

    @Autowired
    private IStudentManageService service;
    @Autowired
    private ITransferService transferService;
    @Resource
    private ChamberMapper chamberMapper;


    /**
     * 前往查看学生页面
     * @param page_no : 当前页
     * @param page_size : 每页存在数
     * @param student_number : 查询的学号
     * @param model
     * @return
     */
    @GetMapping("/toShowInfo")
    public String toShowInfo(@RequestParam(name ="page_no",required = false,defaultValue = "1")int page_no,
                             @RequestParam(name ="page_size",required = false,defaultValue = "5")int page_size,
                             @RequestParam(name ="student_number",required = false)String student_number,
                             Model model) {
        // 分页条件
        Page<StudentInfo> page = service.page(Page.of(page_no,page_size));
        // 学生数据
        List<StudentInfo> infos = service.queryStuInfo(student_number,page);

        model.addAttribute("stuNumber",student_number); // 学号
        model.addAttribute("studentInfo",infos);
        model.addAttribute("query_items",infos.size());
        model.addAttribute("total",page.getTotal()); // 总条数
        model.addAttribute("pages",student_number!=null ? 1:page.getPages());// 总页数
        model.addAttribute("page_no",page_no);
        model.addAttribute("page_size",page_size);

        return "student/showStudentInfo";
    }

    /**
     * 前往添加学生页面
     * @param message : Constants.MESSAGE 传给前端的提示
     * @param model
     * @return
     */
    @GetMapping("/toAddInfo")
    public String toAddInfo(@RequestParam(name = "message",required = false)String message,
                            Model model) {

        // 获取全部学院信息
        List<CollegeInfo> collegeInfos = service.queryCollegeInfo();
        // 获取全部寝室信息
        QueryWrapper<ChamberInfo> wrapper = new QueryWrapper<ChamberInfo>()
                .apply("chamber_bed >chamber_number_of_people");
        List<ChamberInfo> chamberInfos = chamberMapper.queryAllChtInfo(null,wrapper);

        model.addAttribute("collegeInfos",collegeInfos);
        model.addAttribute("chamberInfos",chamberInfos);
        model.addAttribute(Constants.MESSAGE,message);
        return "student/addStudentInfo";
    }

    /**
     * 执行 - 添加学生信息
     * @param imageFile ： 图片文件
     * @param info ： 学生信息
     * @param req
     * @return
     */
    @PostMapping("/add")
    public String addStudentInfo(@RequestParam(name = "imageFile",required = false) MultipartFile imageFile,
                                 StudentInfo info,
                                 HttpServletRequest req,
                                 Model model) {
        if (imageFile.isEmpty()) {
            model.addAttribute(Constants.MESSAGE,"图片为空，请重新上传");
            return "redirect:/studentManage/toAddInfo";
        }
        // 保存图片
        File file = service.saveImg(imageFile,req);
        if (file == null){
            model.addAttribute(Constants.MESSAGE,"上传图片失败");
            return "redirect:/studentManage/toAddInfo";
        }
        // 进行学生信息保存
        System.out.println("保存--------------------------");
        info.setStudentImgName(file.getName());
        String msg = service.addStudentInfo(info);
        if (msg.equals("true")){
            model.addAttribute(Constants.MESSAGE,"添加成功");
        }else{
            // 修改失败删除已上传的照片
            if (!file.delete()) {
                model.addAttribute(Constants.MESSAGE,"添加失败,"+msg+"！删除上传图片失败！");
            }else{
                model.addAttribute(Constants.MESSAGE,"添加失败,"+msg);
            }
        }
        return "redirect:/studentManage/toAddInfo";
    }
    /**
     * 根据学院查找所属专业
     * @param college_id ： 学院id
     * @return
     */
    @GetMapping("/ByCollageIdSpec")
    @ResponseBody
    public Result addByCollageIdSelectSpeciality(@RequestParam("college_id") int college_id) {
        List<SpecialityInfo> infos = service.querySpecialityInfo(college_id);
        return Result.success(infos);
    }
    /**
     * 根据所属专业查找对应班级
     * @param speciality_id ： 专业id
     * @return
     */
    @GetMapping("/BySpecIdClass")
    @ResponseBody
    public Result BySpecIdSelectClass(@RequestParam("speciality_id") int speciality_id) {
        List<ClassInfo> infos = service.queryClassInfo(speciality_id);
        return Result.success(infos);
    }

    /**
     * 执行 - 删除学生信息
     * @param stu_id : 学生id
     * @param chamber_id ： 寝室id
     * @param model
     * @return
     */
    @GetMapping("/delete")
    public String deleteStudentInfo(@RequestParam("stu_id") int stu_id,
                                    @RequestParam("chamber_id") int chamber_id,
                                    HttpServletRequest req,
                                    Model model) {

        int pd = service.deleteStudentInfo(stu_id,chamber_id,req);
        if (pd>0){
            model.addAttribute(Constants.MESSAGE,"删除成功");
        }else{
            model.addAttribute(Constants.MESSAGE,"删除失败");
        }

        return "student/showStudentInfo";
    }

    /**
     * 前往修改学生页面
     * @param stu_id ： 学生id
     * @param message
     * @param model
     * @return
     */
    @GetMapping("/toUpdateInfo")
    public String toUpdateInfo(@RequestParam("stu_id") int stu_id,
                               @RequestParam(name = "message",required = false)String message,
                               Model model) {

        // 根据学生id查找学生信息
        StudentInfo studentInfo = service.queryOneStuInfo(stu_id);
        // 获取全部学院信息
        List<CollegeInfo> collegeInfos = service.queryCollegeInfo();
        // 获取全部寝室信息
        QueryWrapper<ChamberInfo> chamber_wrapper = new QueryWrapper<ChamberInfo>()
                .apply("chamber_bed >chamber_number_of_people");
        List<ChamberInfo> chamberInfos = chamberMapper.queryAllChtInfo(null,chamber_wrapper);

        model.addAttribute("studentInfo",studentInfo);
        model.addAttribute("collegeInfos",collegeInfos);
        model.addAttribute("chamberInfos",chamberInfos);
        model.addAttribute(Constants.MESSAGE,message);
        return "student/updateStudentInfo";
    }

    /**
     * 执行 - 修改学生信息
     * @param info
     * @param oleChamberId
     * @param model
     * @return
     */
    @PostMapping("/update")
    public String updateStudentInfo(StudentInfo info,
                                    @RequestParam("oleChamberId") int oleChamberId,
                                    Model model) {
        System.out.println(info);
        System.out.println("oleChamberId : "+ oleChamberId);

        String msg = service.updateStudentInfo(info,oleChamberId);
        if (msg.equals("true")){
            model.addAttribute(Constants.MESSAGE,"修改成功");
        }else{
            model.addAttribute(Constants.MESSAGE,"修改失败,"+msg);
        }
        model.addAttribute("stu_id",info.getStudentId());
        return "redirect:/studentManage/toUpdateInfo";
    }


    /**
     * 学生权限 - 前往个人信息界面
     * @return
     */
    @GetMapping("/toStuOneInfo")
    public String toAddInfo(HttpServletRequest req,Model model) {

        User user = (User) req.getSession().getAttribute(Constants.USER_SESSION);
        int student_id = user.getUserStudentId();
        // 根据学生id查找学生信息
        StudentInfo studentInfo = service.queryOneStuInfo(student_id);

        model.addAttribute("stu_info",studentInfo);
        return "student/stuInfo";
    }
    /**
     * 学生权限 - 执行 - 更新个人信息
     * @param info
     * @param model
     * @return
     */
    @PostMapping("/updateOneStu")
    public String updateOneStuInfo(@RequestParam(name = "imageFile",required = false) MultipartFile imageFile,
                                   StudentInfo info,
                                   HttpServletRequest req,
                                   Model model) {
        File file = null;
        String old_img_name = "";
        if (!imageFile.isEmpty()) {
            // 保存图片
            file = service.saveImg(imageFile,req);
            if (file == null){
                model.addAttribute(Constants.MESSAGE,"上传图片失败");
                return "redirect:/studentManage/toStuOneInfo";
            }
            // 旧图片，更新成功删除掉
            old_img_name = info.getStudentImgName();
            System.out.println("old_img_name: "+old_img_name);
            System.out.println(info);

            info.setStudentImgName(file.getName());
        }else{
            info.setStudentImgName("");
        }

        // 更新个人信息
        System.out.println("更新--------------------------");

        // 执行更新
        String msg = service.updateUserStuInfo(info);

        if (msg.equals("true")){
            model.addAttribute(Constants.MESSAGE,"更新成功");
            // 删除旧图片 - 不存在旧照片就不删除
            if (!old_img_name.equals("")){
                File dest = new File(req.getServletContext().getRealPath("/img/") + old_img_name);
                if (!dest.delete()) {
                    model.addAttribute(Constants.MESSAGE,"！删除上传图片失败！- 旧");
                }
            }
        }else{
            // 修改失败删除已上传的照片
            if (!file.delete()) {
                model.addAttribute(Constants.MESSAGE,"更新失败,"+msg+"！删除上传图片失败！");
            }else{
                model.addAttribute(Constants.MESSAGE,"更新失败,"+msg);
            }
        }

        User user = (User) req.getSession().getAttribute(Constants.USER_SESSION);
        int student_id = user.getUserStudentId();
        // 根据学生id查找学生信息
        StudentInfo studentInfo = service.queryOneStuInfo(student_id);

        model.addAttribute("stu_info",studentInfo);
        return "student/stuInfo";
    }


    /**
     * 前往调寝审核界面
     * @return
     */
    @GetMapping("/toTransferAuditing")
    public String toTransferAuditing(@RequestParam(name = "message",required = false)String message,
                                     HttpServletRequest req,
                                     Model model) {

        List<TransferChamberInfo> infos = transferService.queryApplyInScheduleInfo();

        model.addAttribute("TransferAuditingInfos",infos);
        model.addAttribute(Constants.MESSAGE,message);

        return "chamber/sleepAdjust/manage_showAdjustmentApply";
    }
    /**
     * 将选中的调寝记录审核打回
     * @return
     */
    @GetMapping("/dangerAuditing")
    public String dangerAuditing(@RequestParam(name = "other_chamber_id")int other_chamber_id,Model model) {

        System.out.println(other_chamber_id);
        boolean pd = transferService.dangerAdjustmentApplyInfo(other_chamber_id);
        if (pd){
            model.addAttribute(Constants.MESSAGE,"打回成功");
        }else{
            model.addAttribute(Constants.MESSAGE,"打回失败");
        }
        return "redirect:/studentManage/toTransferAuditing";
    }
    /**
     * 将选中的调寝记录审核通过
     * @return
     */
    @GetMapping("/successAuditing")
    public String successAuditing(@RequestParam(name = "apply_other_id")int apply_other_id,
                                  @RequestParam(name = "new_chamber_id")int new_chamber_id,
                                  @RequestParam(name = "stu_id")int stu_id,
                                  @RequestParam(name = "old_chamber_id")int old_chamber_id,
                                  Model model) {

        int pd = transferService.successAdjustmentApplyInfo(apply_other_id,old_chamber_id,new_chamber_id,stu_id);
        if (pd>0){
            model.addAttribute(Constants.MESSAGE,"审核通过");
        }else{
            model.addAttribute(Constants.MESSAGE,"审核失败");
        }
        return "redirect:/studentManage/toTransferAuditing";
    }
}
